package com.hxd.mall.module.product.search.result

import android.annotation.SuppressLint
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import androidx.recyclerview.widget.SimpleItemAnimator
import com.hxd.mall.R
import com.hxd.mall.base.BaseInjectFragment
import com.hxd.mall.constant.HxdConstants.IntentParamsKeyDefine.product_skuNo
import com.hxd.mall.constant.HxdConstantsAccount.localSearch
import com.hxd.mall.constant.HxdConstantsAccount.localSearchKey
import com.hxd.mall.constant.HxdConstantsRouterPath.Product.path_hxd_product_detail_page
import com.hxd.mall.module.product.home.bean.HomeProductListBean
import com.hxd.mall.module.product.home.bean.ListBean
import com.hxd.mall.module.product.search.SearchActivity
import com.hxd.mall.module.product.search.adapter.SearchListAdapter
import com.hxd.mall.utils.local.HxdSharePreferenceUtil.saveStringData
import com.hxd.mall.utils.local.NavigationUtil.routerNavigation
import com.hxd.mall.utils.local.search_result_page_view
import com.hxd.mall.utils.local.sendPoint
import com.hxd.mall.utils.open.DataCleanManager.clearCache
import com.hxd.mall.utils.open.GsonUtil
import com.hxd.mall.utils.open.UIUtil.hideKeyboard
import com.hxd.mall.utils.open.addSetOnClickListener
import com.hxd.mall.utils.open.initRecyclerView
import kotlinx.android.synthetic.main.fragment_search_result_layout.*

/**
 * @author zhaoyong
 * @description: 搜索结果
 * @date :2019-10-22 10:50
 */
class SearchResultFragment : BaseInjectFragment<ISearchResultPresenter>(), ISearchResultView {

    private var pageNum = 1
    private var pageSize = 20
    private var moreView: View? = null
    private val adapter = SearchListAdapter()
    private var mCheckindex = 0
    private var mCheckContent = ""
    private var hasCoupon = false
    //是否滑到顶部
    private var isSmartScroll = false

    override fun attachLayoutRes(): Int = R.layout.fragment_search_result_layout

    private fun searchLoad(isLoadMore: Boolean) {
        val key = (activity as SearchActivity).searchText()
        mPresenter?.getListData(isLoadMore, key, pageNum, pageSize, getSort(), hasCoupon.toString())
    }

    override fun initViews() {
        activity?.sendPoint(search_result_page_view)
        addSetOnClickListener(tv_ygsy, tv_total, tv_xl, tv_price) {
            pageNum = 1
            addOnClick(it)
        }

        addSetOnClickListener(iv_hasCoupon) {
            hasCoupon = !hasCoupon
            iv_hasCoupon.setImageResource(if (hasCoupon) R.mipmap.switch_on else R.mipmap.switch_off)
            pageNum = 1

            searchLoad(false)
        }

        //构造无更多数据的布局
        moreView = LayoutInflater.from(activity!!).inflate(R.layout.no_date_layout, null)

        //在内容不满一页的时候，是否可以上拉加载更多
        //smart_refresh_layout.setEnableLoadMoreWhenContentNotFull(false)

        //构造空数据的view
        searchList.initRecyclerView(adapter, padding = 12, leftPadding = 116)
        (searchList.itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false
        // adapter.setEmptyView(R.layout.no_date_layout, searchList)
        adapter.setOnItemClickListener { adapter, _, position ->
            val bean = adapter.getItem(position) as ListBean
            routerNavigation(path_hxd_product_detail_page, mutableMapOf(product_skuNo to bean.no))
        }

        smart_refresh_layout.setOnRefreshListener {
            pageNum = 1
            searchLoad(false)
        }
        adapter.setOnLoadMoreListener({
            //先清除缓存
            clearCache(activity, 100)
            pageNum++

            searchLoad(true)
        }, searchList)

        smart_refresh_layout.setEnableLoadMore(false)
        initData()
    }

    private fun addOnClick(it: View) {
        isSmartScroll = true
        //先将选中的view改变状态
        when (it) {
            tv_total -> {
                tv_total.setTextColor(true)
                tv_xl.setTextColor(false)
                tv_ygsy.setTextColor(false)
                tv_price.setTextColor(false)

                setTextRightPic(tv_xl, R.mipmap.sort_icon)
                setTextRightPic(tv_ygsy, R.mipmap.sort_icon)
                setTextRightPic(tv_price, R.mipmap.sort_icon)
                setTextRightPic(tv_total)
            }
            tv_xl, tv_ygsy -> {
                mCheckContent = if (mCheckContent.isEmpty()) "down" else {
                    if (mCheckindex == it.tag.toString().toInt()) {
                        if (mCheckContent == "down") "up" else "down"
                    } else "down"
                }
                tv_total.setTextColor(false)

                if (it == tv_xl) {
                    tv_xl.setTextColor(true)
                    tv_ygsy.setTextColor(false)
                    tv_price.setTextColor(false)

                    setTextRightPic(tv_xl, if (mCheckContent == "down") R.mipmap.soft_down else R.mipmap.soft_up)
                    setTextRightPic(tv_ygsy, R.mipmap.sort_icon)
                    setTextRightPic(tv_price, R.mipmap.sort_icon)
                    setTextRightPic(tv_total)
                } else {
                    tv_ygsy.setTextColor(true)
                    tv_xl.setTextColor(false)
                    tv_price.setTextColor(false)

                    setTextRightPic(tv_ygsy, if (mCheckContent == "down") R.mipmap.soft_down else R.mipmap.soft_up)
                    setTextRightPic(tv_xl, R.mipmap.sort_icon)
                    setTextRightPic(tv_price, R.mipmap.sort_icon)
                    setTextRightPic(tv_total)
                }
            }
            tv_price -> {
                mCheckContent = if (mCheckContent.isEmpty()) "up" else {
                    if (mCheckindex == it.tag.toString().toInt()) {
                        if (mCheckContent == "down") "up" else "down"
                    } else "up"
                }

                tv_price.setTextColor(true)
                tv_xl.setTextColor(false)
                tv_ygsy.setTextColor(false)
                tv_total.setTextColor(false)

                setTextRightPic(tv_price, if (mCheckContent == "down") R.mipmap.soft_down else R.mipmap.soft_up)
                setTextRightPic(tv_xl, R.mipmap.sort_icon)
                setTextRightPic(tv_ygsy, R.mipmap.sort_icon)
                setTextRightPic(tv_total)
            }
        }

        mCheckindex = it.tag.toString().toInt()

        searchLoad(false)

        Log.d("mCheckindex", "$mCheckindex  $mCheckContent")
    }

    override fun initData() {
        val key = (activity as SearchActivity).searchText()
        //排重，再添加
        val find = localSearch.indexOfFirst { it == key }
        if (find != -1) {
            localSearch.removeAt(find)
        }
        if (localSearch.size > 0) {
            localSearch.add(0, key)
        } else {
            localSearch.add(key)
        }
        if (localSearch.size > 10) {
            localSearch.removeAt(localSearch.size - 1)
        }
        saveStringData(localSearchKey, GsonUtil.bean2json(localSearch))

        hideKeyboard(chose_layout)

        searchLoad(false)
    }

    override fun showData(t: HomeProductListBean) {
        no_data.visibility = View.GONE
        smart_refresh_layout.visibility = View.VISIBLE
        t.data?.list?.run {
            if (this.isNotEmpty()) {
                if (pageNum == 1) {
                    adapter.setNewData(this)
                } else {
                    adapter.addData(this)
                }

                adapter.removeAllFooterView()
                //结束刷新
                if (t.data?.isLastPage == true) {
                    //if (pageNum != 1)
                    adapter.addFooterView(moreView)
                    adapter.setEnableLoadMore(false)
                    adapter.loadMoreEnd()
                } else {
                    adapter.setEnableLoadMore(true)
                }
                hideKeyboard(smart_refresh_layout)
            } else {
                adapter.loadMoreEnd()
                adapter.setEnableLoadMore(false)
                if (pageNum > 1) {
                    adapter.removeAllFooterView()
                    adapter.addFooterView(moreView)
                }
            }
            if (isSmartScroll) {
                isSmartScroll = false
                searchList.scrollToPosition(0)
            }
        }
        isShowEmptyView()
    }

    private fun isShowEmptyView() {
        if (adapter.data.size == 0) {
            no_data?.visibility = View.VISIBLE
            smart_refresh_layout?.visibility = View.GONE
        } else {
            no_data?.visibility = View.GONE
            smart_refresh_layout?.visibility = View.VISIBLE
        }
    }

    override fun finishRefresh() {
        smart_refresh_layout?.finishRefresh()
        adapter.loadMoreComplete()
    }

    override fun finishFailRefresh() {
        smart_refresh_layout?.finishRefresh()
        adapter.loadMoreFail()
    }

    @SuppressLint("SetTextI18n")
    private fun setSeleteBg(tv: TextView, soft: String) {
        tv.setCompoundDrawablesWithIntrinsicBounds(
            null, null, when (soft) {
                "up" -> {
                    tv.setTextColor(resources.getColor(R.color.color_E24840))
                    resources.getDrawable(R.mipmap.soft_up)
                }
                "down" -> {
                    tv.setTextColor(resources.getColor(R.color.color_E24840))
                    resources.getDrawable(R.mipmap.soft_down)
                }
                else -> {
                    tv.setTextColor(resources.getColor(R.color.color_333333))
                    resources.getDrawable(R.mipmap.sort_icon)
                }
            }, null
        )
    }

    private fun getSort() = when (mCheckindex) {
        0 -> ""
        1 -> if (mCheckContent == "up") "total_sales_asc" else "total_sales_des"
        2 -> if (mCheckContent == "up") "tk_rate _asc" else "tk_rate_des"
        3 -> if (mCheckContent == "up") "price_asc" else "price_des"
        else -> ""
    }


    private fun setTextRightPic(textView: TextView, drawable: Int? = null) {
        textView.setCompoundDrawablesWithIntrinsicBounds(null, null, if (drawable == null) null else resources.getDrawable(drawable), null)
    }

    private fun TextView.setTextColor(check: Boolean) {
        if (check)
            setTextColor(resources.getColor(R.color.color_E24840))
        else
            setTextColor(resources.getColor(R.color.color_333333))
    }


}